﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.Models;

namespace Core.Controllers
{
    [Permission("Can Administer Tags")]
    public class TagController : Controller
    {
        //
        // GET: /Tag/

        public ActionResult Index(Guid id)
        {
            CoreEntities core = new CoreEntities();
            TagCategory tc = core.TagCategories.First(t => t.TagCategoryId == id);
            ViewBag.TagCategoryId = id;
            ViewBag.TagCategoryName = tc.TagCategoryName;
            return View();
        }

        //
        // POST: /Tag/TagList/

        [HttpPost]
        public JsonResult TagList(FormCollection collection)
        {
            CoreEntities core = new CoreEntities();
            Guid TCId = new Guid(collection.GetValues("TagCategoryId")[0].ToString());
            int SkipRecs = int.Parse(collection.GetValues("iDisplayStart")[0].ToString());
            int TakeCount = int.Parse(collection.GetValues("iDisplayLength")[0].ToString());
            string strSearch = collection.GetValues("sSearch")[0].ToString();
            DataTableResponse r = new DataTableResponse();
            // Needs update when paging & sorting is implemented
            List<Tag> list = core.Tags.Where(m => (m.TagCategoryId == TCId && m.TagName.Contains(strSearch) && m.IsDroppedYN == "N")).OrderBy(m => m.TagName).Skip(SkipRecs).Take(TakeCount).ToList();
            r.sEcho = collection.GetValues("sEcho")[0].ToString();
            // This query is required because the earlier query returns results for only 1 page.
            r.iTotalRecords = core.Tags.Where(m => (m.TagCategoryId == TCId && m.TagName.Contains(strSearch) && m.IsDroppedYN == "N")).Count();
            r.iTotalDisplayRecords = r.iTotalRecords;
            foreach (Tag t in list)
            {
                List<string> r1 = new List<string>();
                string editurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"editlink\" title=\"{1}\" >Edit</a>", "Tag", "Edit", t.TagId.ToString());
                string detailsurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"detailslink\" title=\"{1}\" >Details</a>", "Tag", "Details", t.TagId.ToString());
                string deleteurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"deletelink\" title=\"{1}\" >Delete</a>", "Tag", "Delete", t.TagId.ToString());
                r1.Add(editurl + detailsurl + deleteurl);
                r1.Add(t.TagName);
                r1.Add(String.Format("{0:g}", t.ModifiedDT));
                r1.Add(t.ModifiedByName);
                r1.Add(String.Format("{0:g}", t.CreateDT));
                r1.Add(t.CreatedByName);
                r.aaData.Add(r1);
            }
            return Json(r);
        }

        //
        // GET: /Tag/Details/5

        public ActionResult Details(Guid id)
        {
            CoreEntities core = new CoreEntities();
            Tag tag = core.Tags.First(t => t.TagId == id);
            return View(tag);
        }

        //
        // GET: /Tag/Create

        public ActionResult Create(Guid id)
        {
            Tag t = new Tag();
            t.TagCategoryId = id;
            CoreEntities core = new CoreEntities();
            TagCategory tc = core.TagCategories.First(m => m.TagCategoryId == id);
            t.BusinessUnitId = tc.BusinessUnitId;            
            return View(t);
        } 

        //
        // POST: /Tag/Create

        [HttpPost]
        public ActionResult Create(Tag t)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    t.TagId = Guid.NewGuid();
                    if (t.BusinessUnitId.Equals(Guid.Empty)) t.BusinessUnitId = null;
                    t.IsDroppedYN = "N";
                    t.CreateDT = DateTime.Now;
                    t.CreatedById = (Guid)Session["UserId"];
                    t.CreatedByName = Session["UserFullName"].ToString();
                    t.ModifiedDT = DateTime.Now;
                    t.ModifiedById = (Guid)Session["UserId"];
                    t.ModifiedByName = Session["UserFullName"].ToString();
                    CoreEntities core = new CoreEntities();
                    core.AddToTags(t);
                    core.SaveChanges();
                    return RedirectToAction("Index", new { id = t.TagCategoryId });
                }
                else
                    return View(t);
            }
            catch(Exception e)
            {
                ModelState.AddModelError("", Tools.ExceptionMessage(e));
                return View(t);
            }
        }
        
        //
        // GET: /Tag/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            CoreEntities core = new CoreEntities();
            Tag tag = core.Tags.First(t => t.TagId == id);
            return View(tag);
        }

        //
        // POST: /Tag/Edit/5

        [HttpPost]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    CoreEntities core = new CoreEntities();
                    Tag t = core.Tags.First(b => b.TagId == id);
                    UpdateModel(t, collection.ToValueProvider());
                    t.ModifiedDT = DateTime.Now;
                    t.ModifiedById = (Guid)Session["UserId"];
                    t.ModifiedByName = Session["UserFullName"].ToString();
                    core.SaveChanges();
                    return RedirectToAction("Index", new { id = t.TagCategoryId});
                }
                else
                    return View();
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Tag/Delete/5
 
        public ActionResult Delete(Guid id)
        {
            CoreEntities core = new CoreEntities();
            Tag tag = core.Tags.First(t => t.TagId == id);
            return View(tag);
        }

        //
        // POST: /Tag/Delete/5

        [HttpPost]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                if (ModelState.IsValid)
                {
                    CoreEntities core = new CoreEntities();
                    Tag t = core.Tags.First(b => b.TagId == id);
                    t.IsDroppedYN = "Y";
                    t.ModifiedDT = DateTime.Now;
                    t.ModifiedById = (Guid)Session["UserId"];
                    t.ModifiedByName = Session["UserFullName"].ToString();
                    core.SaveChanges();
                    return RedirectToAction("Index", new { id = t.TagCategoryId });
                }
                else
                    return View();
            }
            catch
            {
                return View();
            }
        }
    }
}
